package com.sk.bilibili.apiMapper.component;

import com.sk.bilibili.apiMapper.bean.Args;
import com.sk.bilibili.apiMapper.bean.RequestInfo;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 邵康
 * @date 2021/7/11 8:31
 */
public class RequestHandler {

    private HttpSender httpSender;
    private JsonHandler jsonHandler;
    private static final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)}");

    public void setHttpSender(HttpSender httpSender) {
        this.httpSender = httpSender;
    }

    public void setJsonHandler(JsonHandler jsonHandler) {
        this.jsonHandler = jsonHandler;
    }

    public Object handleRequest(RequestInfo request, Args args){
        String url=buildUrl(request.getUrl(),args.getArgs());
        String json=httpSender.send(url,request.getMethod(),request.getAddHeaders(),request.getRemoveHeaders(),
                args);
        return jsonHandler.handleJson(json,request.getReturnClass(),request.getPath());
    }

    private String buildUrl(String url, Map<String, Object> args) {
        Matcher matcher = PATTERN.matcher(url);
        StringBuffer buffer=new StringBuffer();
        while (matcher.find()){
            Object arg = args.get(matcher.group(1));
            if(arg==null)throw new RuntimeException("没人传入参数:"+matcher.group(1));
            matcher.appendReplacement(buffer,arg.toString());
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }

}
